import 'braft-editor/dist/index.css'
import React, { PureComponent } from 'react'
import { connect } from 'dva'
import { Card, message, Spin } from 'antd'
import { cloneDeep, isEqual } from 'lodash'

import { PageHeaderWrapper } from '@ant-design/pro-layout'
import goodsService from '@/services/goods'
import template from '@/services/template'
import MainForm from '@/pages/Template/goodsForm'
import { router } from 'umi'
import shopAdditionalService from '@/services/shopAdditional'
import busShopService from '@/services/busShop'
import RouterWillLeave from '@/components/RouterWillLeave'

@connect(({ goodsDetail, loading }) => ({
  goodsDetail,
  loading: loading.models.goodsDetail
}))
class GoodsDetail extends PureComponent {
  state = {
    id: '',
    buyOutValue: 0,
    loading: false,
    goodsDetail: {},
    categories: [],
    addServiceTableData: [],
    districts: [],
    giveBackList: [],
    shopAdditionServiceList: []
  }

  componentWillMount() {
    const {
      match: {
        params: { id }
      }
    } = this.props

    this.findCategories()
    this.getShopAdditionalServiceList()
    this.getGiveBackList()
    this.selectDistrict()
    if (id && id !== 'add') {
      this.getShopAdditionServiceList()
      this.getData(id)
    } else {
      this.getShopAdditionServiceList()
      // 给一个商品的初始化的数据
      this.setState({
        goodsDetail: {
          name: '',
          oldNewDegree: 1,
          labels: [],
          additionals: null,
          shopAdditionals: [],
          hasBroken: false, // false - 否； true - 是
          buyOutSupport: 1,
          productSkuses: [],
          minRentCycle: '',
          maxRentCycle: '',
          type: 1,
          detail: '',
          province: '',
          city: '',
          freightType: 'PAY',
          addIds: [],
          images: [],
          src: null,
          productId: '',
          salesVolume: null,
          lowestSalePrice: null,
          parameters: [],
          productCouponList: null,
          collected: null,
          specs: [
            { name: '套餐', opeSpecId: 1, values: [] },
            { name: '颜色', opeSpecId: 2, values: [] },
            {
              name: '规格',
              opeSpecId: 3,
              values: []
            }
          ],
          serviceTel: null,
          rentCycle: 365,
          rentPeriodsType: 3,
          rentPeriods: '',
          rentDays: ''
        },
        id
      })
    }
  }

  // 增值服务下拉框数据
  getShopAdditionServiceList = () => {
    goodsService.getShopAdditionServiceList().then(res => {
      const data = res.httpStatus ? [] : res
      this.setState({
        shopAdditionServiceList: data || []
      })
    })
  }
  

  getData = (id = this.state.id) => {
    this.setState({
      loading: true
    })
    goodsService
      .selectProductEdit({
        id
      })
      .then(res => {
        const tmpRes = { ...res }
        tmpRes.rentCycle = res.maxRentCycle
        this.setState({
          buyOutValue: 0,
          goodsDetail: tmpRes,
          id,
          editShopAdditionServiceList: tmpRes.additionals
        })
      })
      .finally(() => {
        this.setState({
          loading: false
        })
      })
  }

  findCategories = () => {
    goodsService.findCategories().then(res => {
      const data = res.httpStatus ? [] : res
      this.setState({
        categories: data || []
      })
    })
  }

  getShopAdditionalServiceList = () => {
    shopAdditionalService
      .selectShopAdditionalServicesList({
        pageSize: 9999,
        pageNumber: 1,
        name: ''
      })
      .then(res => {
        // message.success('获取数据成功')
        this.setState({
          addServiceTableData: res.records || []
        })
      })
  }

  selectDistrict = () => {
    goodsService.selectDistrict().then(res => {
      const data = res.httpStatus ? [] : res
      this.setState({
        districts: data || []
      })
    })
  }

  getGiveBackList = () => {
    busShopService.selectShopRuleAndGiveBackByShopId().then(res => {
      const data = res.httpStatus ? [] : res
      this.setState({
        giveBackList: data || []
      })
    })
  }

  setInitList = () => {
    const { dispatch } = this.props
    dispatch({
      type: 'goodsDetail/selectShopRuleAndGiveBackByShopId'
    })
  }

  // 改变规格，改变之后重新处理sku的渲染
  changeSpecs = (specs, opeSpecId) => {
    const { goodsDetail } = this.state
    const _goodsDetail = cloneDeep(goodsDetail)
    _goodsDetail.specs = _goodsDetail.specs.map(f => {
      if (f.opeSpecId === opeSpecId) {
        return specs
      }
      return f
    })
    this.setState(
      {
        goodsDetail: _goodsDetail
      },
      () => {
        this.handleSku()
      }
    )
    // const old_specs = _goodsDetail.specs.find(f=> f.opeSpecId !== _type).values
  }

  // 处理SKu渲染的逻辑
  handleSku = () => {
    const { goodsDetail } = this.state
    const _goodsDetail = cloneDeep(goodsDetail)
    let _specs = {}
    let colorSpecs = {}
    let productPackage = {}
    _goodsDetail.specs.forEach(v => {
      if (v.opeSpecId === 1) {
        productPackage = v
      } else if (v.opeSpecId === 2) {
        colorSpecs = v
      } else {
        _specs = v
      }
    })
    const _productSkuses = _goodsDetail.productSkuses
    const productPackageLength = productPackage.values.length
    const colorSpecsLength = colorSpecs.values.length
    const specsLength = _specs.values.length
    const _arr = []
    for (let k = 0; k < productPackageLength; k++) {
      for (let i = 0; i < colorSpecsLength; i++) {
        for (let j = 0; j < specsLength; j++) {
          const index_p = _productSkuses.findIndex(_p => {
            return (
              _p.specAll[0].platformSpecValue ===
                productPackage.values[k].name &&
              _p.specAll[1].platformSpecValue === colorSpecs.values[i].name &&
              _p.specAll[2].platformSpecValue === _specs.values[j].name
            )
          })
          if (index_p > -1) {
            _arr.push(_productSkuses[index_p])
          } else {
            _arr.push({
              cycs: [
                {
                  days: _goodsDetail.rentCycle ? _goodsDetail.rentCycle : '',
                  price: '',
                  salePrice: ''
                }
              ],
              depositPrice: null,
              inventory: '',
              marketPrice: '',
              platformSpecValue: null,
              specAll: [
                {
                  opeSpecId: 1,
                  platformSpecName: '套餐',
                  platformSpecValue: productPackage.values[k].name
                },
                {
                  opeSpecId: 2,
                  platformSpecName: '颜色',
                  platformSpecValue: colorSpecs.values[i].name
                },
                {
                  opeSpecId: 3,
                  platformSpecName: '规格',
                  platformSpecValue: _specs.values[j].name
                }
              ]
            })
          }
        }
      }
    }
    _goodsDetail.productSkuses = _arr
    this.setState({
      goodsDetail: _goodsDetail
    })
  }

  changeSku = (sku, index) => {
    console.log('sku:')
    console.log(sku)
    console.log(index)
    const { goodsDetail } = this.state
    const _goodsDetail = cloneDeep(goodsDetail)
    _goodsDetail.productSkuses[index] = sku
    this.setState({
      goodsDetail: _goodsDetail
    })
  }

  deleteSku = index => {
    const { goodsDetail } = this.state
    const _goodsDetail = cloneDeep(goodsDetail)
    _goodsDetail.productSkuses.splice(index, 1)
    this.setState({
      goodsDetail: _goodsDetail
    })
  }

  deleteSpecs = (specs, index) => {
    const { goodsDetail } = this.state
    const _goodsDetail = cloneDeep(goodsDetail)
    _goodsDetail.specs = specs
    _goodsDetail.productSkuses.splice(index, 1)
    this.setState({
      goodsDetail: _goodsDetail
    })
  }

  handleSubmit = data => {
    const { goodsDetail, id } = this.state
    const { categoryIds = [] } = data
    const isAdd = id && id !== 'add'
    const service = isAdd
      ? goodsService.updateBusProduct
      : template.insertProductTemplate
    const _goodsDetail = cloneDeep(goodsDetail)
    const _data = cloneDeep(data)
    console.log(_data)
    if (
      Number.isInteger(parseInt(_data.rentPeriods)) &&
      Number.isInteger(parseInt(_data.rentDays))
    ) {
      if (_data.rentPeriodsType == 1) {
        _goodsDetail.rentCycle =
          _goodsDetail.rentPeriods * _goodsDetail.rentDays
        _goodsDetail.minRentCycle = _goodsDetail.rentCycle
        _goodsDetail.maxRentCycle = _goodsDetail.rentCycle
        _data.rentCycle = _data.rentPeriods * _data.rentDays
        _data.minRentCycle = _data.rentCycle
        _data.maxRentCycle = _data.rentCycle
        this.setState({
          goodsDetail: _goodsDetail
        })
      }

      if (_data.rentPeriodsType == 2) {
        _goodsDetail.rentCycle =
          _goodsDetail.rentPeriods * _goodsDetail.rentDays * 7
        _goodsDetail.minRentCycle = _goodsDetail.rentCycle
        _goodsDetail.maxRentCycle = _goodsDetail.rentCycle
        _data.rentCycle = _data.rentPeriods * _data.rentDays * 7
        _data.minRentCycle = _data.rentCycle
        _data.maxRentCycle = _data.rentCycle
        this.setState({
          goodsDetail: _goodsDetail
        })
      }

      if (_data.rentPeriodsType == 3) {
        _goodsDetail.rentCycle =
          _goodsDetail.rentPeriods * _goodsDetail.rentDays * 31
        _goodsDetail.minRentCycle = _goodsDetail.rentCycle
        _goodsDetail.maxRentCycle = _goodsDetail.rentCycle
        _data.rentCycle = _data.rentPeriods * _data.rentDays * 31
        _data.minRentCycle = _data.rentCycle
        _data.maxRentCycle = _data.rentCycle
        this.setState({
          goodsDetail: _goodsDetail
        })
      }

      return service({
        ...goodsDetail,
        ..._data,
        specs: goodsDetail.specs,
        categoryId: categoryIds[categoryIds.length - 1],
        id: id === 'add' ? null : id
      }).then(res => {
        const msg = isAdd ? '新增成功' : '更新成功'
        message.success(msg)
        this.cancel()
      })
    } else {
      message.warning('租赁周期请填写整数')
      return false
    }
  }

  onProductBuyout = value => {
    this.setState({
      buyOutValue: value
    })
  }

  cancel = (isPrompt, isSubmit) => {
    this.setState(
      {
        isPrompt,
        isSubmit
      },
      () => {
        router.push('/template/list')
      }
    )
  }

  renderRouterWillLeave() {
    const { isPrompt, isSubmit } = this.state
    return <RouterWillLeave isPrompt={isPrompt} isSubmit={isSubmit} />
  }

  render() {
    const {
      loading,
      buyOutValue,
      id,
      goodsDetail,
      categories,
      addServiceTableData,
      districts,
      giveBackList,
      shopAdditionServiceList,
      editShopAdditionServiceList
    } = this.state

    const title = id === 'add' ? '新增模板' : '修改模板'

    return (
      <PageHeaderWrapper title={title}>
        <Spin spinning={loading}>
          <Card>
            {/* { */}
            {/*  this.renderRouterWillLeave() */}
            {/* } */}
            {goodsDetail && (
              <MainForm
                goodsDetail={goodsDetail}
                categories={categories}
                addServiceTableData={addServiceTableData}
                changeSpecs={this.changeSpecs}
                deleteSpecs={this.deleteSpecs}
                changeSku={this.changeSku}
                deleteSku={this.deleteSku}
                districts={districts}
                giveBackList={giveBackList}
                handleSubmit={this.handleSubmit}
                setInitList={this.setInitList}
                editType={id}
                cancel={this.cancel}
                buyOutValue={buyOutValue}
                onProductBuyout={value => this.onProductBuyout(value)}
                shopAdditionServiceList={shopAdditionServiceList}
                editShopAdditionServiceList={editShopAdditionServiceList}
              />
            )}
          </Card>
        </Spin>
      </PageHeaderWrapper>
    )
  }
}

export default GoodsDetail
